﻿using MabuCommX;
using ReflectionStudio.Core.Events;
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
namespace WPFExcelReport
{

    /// <summary>
    /// Interaction logic for SETUPABON.xaml
    /// </summary>
    public partial class JLTWB10IT : Window
    {
        public const int WM_COPYDATA = 0x004A;
        [DllImport("User32.dll", CharSet = CharSet.Unicode,CallingConvention=CallingConvention.Cdecl)]
        public static extern IntPtr SendMessage(long hwnd, int wMsg, IntPtr wParam, ref COPYDATASTRUCT lParam);
        //public static extern int SendMessage(long hwnd, IntPtr msg, IntPtr wParam, ref COPYDATASTRUCT lParam); public static extern IntPtr SendMessage(long hwnd, int wMsg, IntPtr wParam, ref COPYDATASTRUCT lParam);

        public string RUNID = "";
        ApplicationBase app
        {
            get
            {
                return ApplicationBase.Instance;
            }
        }
        string company
        {
            get
            {
                return app.company;
            }
        }
        #region ==LENGTH===========
        public static readonly DependencyProperty LENGTHProperty = DependencyProperty.Register("LENGTH",
            typeof(string), typeof(JLTWB10IT),
            new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnLENGTHChanged));
        public string LENGTH
        {
            get
            {
                return (string)GetValue(LENGTHProperty);
            }
            set
            {
                SetValue(LENGTHProperty, value);
            }
        }
        private static void OnLENGTHChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var src = sender as JLTWB10IT;
            if (src != null)
            {
                src.LENGTH = (string)e.NewValue;
            }
        }
        #endregion
        #region ==WBEWBELEG===========
        public static readonly DependencyProperty WBEWBELEGProperty = DependencyProperty.Register("WBEWBELEG",
            typeof(string), typeof(JLTWB10IT),
            new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnWBEWBELEGChanged));
        public string WBEWBELEG
        {
            get
            {
                return (string)GetValue(WBEWBELEGProperty);
            }
            set
            {
                SetValue(WBEWBELEGProperty, value);
            }
        }
        private static void OnWBEWBELEGChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var src = sender as JLTWB10IT;
            if (src != null)
            {
                src.WBEWBELEG = (string)e.NewValue;
            }
        }
        #endregion
        public ReadWrong ReadWrong
        {
            get;
            set;
        }

        public comm MABU
        {
            get;
            set;
        }
        public ReadCounterSpeed MABUJ
        {
            get;
            set;
        }
        VJLTWB10IT vm;
        System.Timers.Timer aTimer = new System.Timers.Timer();
        System.Timers.Timer bTimer = new System.Timers.Timer();

        public JLTWB10IT()
        {
            InitializeComponent();
            this.Name = "标签格式";
            //Setup();
        }

        public void Setup()
        {
            vm = new VJLTWB10IT();
            this.DataContext = vm;
            aTimer.Interval = 200;
            aTimer.Elapsed += aTimer_Elapsed;
            
            bTimer.Interval = 200;
            bTimer.Elapsed += bTimer_Elapsed;
            IsRun = true;
            this.Name = "标签格式";
            //WBEWBELEG = TWBBEW.Instance.GetLastBELEG(vm.TERMNO);
            RUNID = vm.TERMNO;
            try
            {
                if (MABU == null)
                {
                    MABU = new comm();
                    MABUJ = new ReadCounterSpeed();
                    ReadWrong = new ReadWrong();
                    MABU.Settings = "19200,n,8,1";
                    MABU.wait = 100;
                    MABU.CommPort = 1;
                    MABU.CollectImpl = (_ICollect)MABUJ;
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        void aTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (!IsRun)
                aTimer.Stop();
            Task.Factory.StartNew(() => Task.Factory.StartNew(() => GetLength(), new CancellationTokenSource().Token, TaskCreationOptions.None, _sync).Wait());

        }
        //1.1 X +1111111111 2222 333 +4444444444”
        public string hwndQI = "", IFQI = "";
        long WINDOW_HANDLER;          // 存放实例1中的Form1窗口的窗口句柄    
        public readonly TaskScheduler _sync = TaskScheduler.FromCurrentSynchronizationContext();
        public JLTWB10IT(StartupEventArgs e)
        {
            if (e.Args.Length > 0)
            {
                hwndQI = (string)e.Args[2];
                IFQI = (string)e.Args[3];
                WINDOW_HANDLER = Convert.ToInt64(hwndQI);
                MessageBox.Show(e.Args[0].ToString() + Environment.NewLine + e.Args[1].ToString() + Environment.NewLine + e.Args[2].ToString() + Environment.NewLine + e.Args[3].ToString());
            } 
            if (app.EnvExe == null)
                app.Load();
            InitializeComponent();
            Setup();
        }

        public void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                //AutoRun();
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
      
        public void AutoRun()
        {
            IsRun = true;
            aTimer.Start();
        }
        public void GetLength()
        {
            try
            {
                MABU.wait = 100;
                //MABU.ExecuteCommand();
                if (!MABU.ExecuteCommand())
                    return;
                LENGTH = Convert.ToString(MABUJ.Counter);
                if (MABUJ.UnitFlag.ToString() == "1")
                {
                    LENGTH = (Helpers.Helper.RoundX(Convert.ToDouble(LENGTH) * 0.9144, 100)).ToString();
                }
                SEND2QI(Convert.ToDouble(LENGTH));
                if (Convert.ToDouble(LENGTH) == 0)
                {
                    QINEWWB();
                }
            }
            catch (Exception ex)
            {
                //MESSAGE = ex.Message;
                //MessageBox.Show(ex.Message+LENGTH,ex.StackTrace);
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        bool IsRun = false;
        public void QINEWWB()
        {
            MessageInfo msgs = new MessageInfo();
            string msg = "";
            msgs.MSGTYPE = "QINEWWB";
            msgs.Sender = this.RUNID;
            msgs.ACTION = "QINEWWB";
            msgs.P1 = vm.TERMNO;
            msgs.P2 = WBEWBELEG;
            msgs.Where = app.User;
            VICC_WFEVENTS.SVWF.CheckEvents("UIMESSAGE", null, msg, msgs); 
        }
        private void btnStop_Click(object sender, RoutedEventArgs e)
        {
            IsRun = false;
        }
        private void btnGetCount_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //aTimer.Start();
                GetLength();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.StackTrace, ex.Message);
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        public void SEND2QI(double qty)
        {
            //hwndQI = "+0001509980";
            //WINDOW_HANDLER = Convert.ToInt64(hwndQI);
            //string interfaceno = "0004";
          //double LG = Helpers.Helper.RoundX(Convert.ToDouble(LENGTH), 100);
            int idx = 0;
            idx = qty.ToString().IndexOf(".");
            string msg = IFQI + "X" + "BRUTLG.QI03=" + qty.ToString().Substring(0, idx) + "," + Helpers.Helper.Left(qty.ToString().Substring(idx + 1) + "00", 2) + "  ";
            byte[] sarr = System.Text.Encoding.Default.GetBytes(msg);
            int len = sarr.Length;
            COPYDATASTRUCT cds;
            IntPtr rtnmsg;
            cds.dwData = (IntPtr)3;
            cds.cbData = (IntPtr)(len + 1);
            cds.lpData = Marshal.AllocHGlobal(sarr.Length);
            Marshal.Copy(sarr, 0, cds.lpData, sarr.Length);
            rtnmsg = SendMessage(WINDOW_HANDLER, WM_COPYDATA, (IntPtr)0, ref cds);
            txtInfo.Text = WINDOW_HANDLER.ToString() + Environment.NewLine + ":rtnmsg:" + rtnmsg + Environment.NewLine + "*msg*" + msg;
          
          // [DllImport("user32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
            //public static extern IntPtr SendMessage(long hwnd, int wMsg, IntPtr wParam, ref COPYDATASTRUCT lParam);
            //MessageBox.Show(WINDOW_HANDLER.ToString() + ":rtnmsg:" + rtnmsg + msg);
        }
        /*
        public void SEND2QITEST()
        {
            //hwndQI = "+0001509980";
            //WINDOW_HANDLER = Convert.ToInt64(hwndQI);
            //string interfaceno = "0004";
            double LG = Helpers.Helper.RoundX(Convert.ToDouble(LENGTH), 100);
            int idx = 0;
            idx = LG.ToString().IndexOf(".");
            string msg = IFQI + "X" + "BRUTLG.QI03=" + LG.ToString().Substring(0, idx) + "," + Helpers.Helper.Left(LG.ToString().Substring(idx + 1) + "00", 2) + "  ";
            byte[] sarr = System.Text.Encoding.Default.GetBytes(msg);
            int len = sarr.Length;
            COPYDATASTRUCT cds;
            IntPtr rtnmsg;
            cds.dwData = (IntPtr)3;
            cds.cbData = (IntPtr)(len + 1);
            cds.lpData = Marshal.AllocHGlobal(sarr.Length);
            //cds.lpData = msg;
            Marshal.Copy(sarr, 0, cds.lpData, sarr.Length);
            rtnmsg = MabuCommAPI.SendMessage(WINDOW_HANDLER, MabuCommAPI.WM_COPYDATA, (IntPtr)0, ref cds);
            txtInfo.Text = WINDOW_HANDLER.ToString() + Environment.NewLine + ":rtnmsg:" + rtnmsg + Environment.NewLine+ msg;
            // [DllImport("user32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
            //public static extern IntPtr SendMessage(long hwnd, int wMsg, IntPtr wParam, ref COPYDATASTRUCT lParam);
            //MessageBox.Show(WINDOW_HANDLER.ToString() + ":rtnmsg:" + rtnmsg + msg);
        }
        public void SEND2QITEST(double qty)
        {
           
            int idx = 0;
            idx = qty.ToString().IndexOf(".");

            string msg = IFQI + "X" + "BRUTLG.QI03=" + qty.ToString().Substring(0, idx) + "," + Helpers.Helper.Left(qty.ToString().Substring(idx + 1) + "00", 2) + "  ";
            byte[] arr = System.Text.Encoding.Default.GetBytes(msg);
            int len = arr.Length;
            COPYDATASTRUCT cdata;
            cdata.dwData = 3;
            cdata.lpData = msg;
            cdata.cbData =msg.Length + 1;
            int rtnmsg = SendMessage(WINDOW_HANDLER, WM_COPYDATA, 10, ref cdata);
            txtInfo.Text = WINDOW_HANDLER.ToString() + Environment.NewLine + ":rtnmsg:" + rtnmsg + Environment.NewLine + msg;
            MessageBox.Show(txtInfo.Text);
        }
         * */
        private void btnSnd2Itnex_Click_1(object sender, RoutedEventArgs e)
        {
            WINDOW_HANDLER = 725448;
            IFQI = "0003";
            SEND2QI(212.12);
            ///bTimer.Start(); 
        }
        void bTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
             Random rand = new Random();
             double qty = rand.NextDouble();
             SEND2QI(qty);

        }
    }
}
